package com.sdy.controller;


import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.sdy.entity.User;
import com.sdy.service.UserService;
import com.sdy.util.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.util.UUID;

/**
 * @program: ssm1205-2
 * @author: sdy
 * @create: 2022-12-05 16:55
 **/
@RestController
public class UserController {
    @Autowired
    private UserService userService;
    @RequestMapping("/login")
    public R login(User user, HttpSession session) {
        int i = userService.login(user);
        if (i==0){
            return  R.fail("登陆失败，用户名不存在！");
        }
        if (i==1){
            session.setAttribute("username",user.getUsername());
            return R.ok(null);
        }
        if (i==2){
            return R.fail("登陆失败，密码错误！");
        }
        return null;
    }

    @RequestMapping("/admin/logout")
    public R logout(HttpSession session){
        session.invalidate();
        return R.ok("退出成功，请重新登陆！");
    }

    @RequestMapping("/register")
    public R register(User user, String password2, String yzm, MultipartFile tx, HttpSession session,HttpServletRequest request) throws IOException {
        System.out.println(user);
        if (!user.getPassword().equals(password2)){
//            密码不一致
            return R.fail("注册失败！密码不一致！");
        }
        String yzm1 = (String) session.getAttribute("yzm");
        if (!yzm1.equalsIgnoreCase(yzm)){
            session.setAttribute("yzm","");
            return R.fail("注册失败！验证码输入错误！");
        }

        //获取原文件名
        String originalFilename = tx.getOriginalFilename();
        System.out.println(originalFilename);

        //写入文件
//            重命名：防止覆盖
        String  newFileName= UUID.randomUUID()+originalFilename.substring(originalFilename.lastIndexOf("."));
        String path=request.getServletContext().getRealPath("\\upload")+"\\"+newFileName;
        File file=new File(path);
        tx.transferTo(file);
        user.setTxFileName(newFileName);

        int i = userService.register(user);
        if (i==0){
//            未知错误
            return R.fail("注册失败！请联系管理员！");
        }
        if (i==1){
//            注册成功
            session.setAttribute("username",user.getUsername());
            return R.ok("注册成功！请登录！");
        }
        if (i==2){
//            用户存在
            return R.fail("注册失败！用户已存在！");
        }
        return null;
    }

    @RequestMapping("/getImg")
    public void getTx(HttpServletRequest request,HttpServletResponse response) throws IOException {
        String username =(String) request.getSession().getAttribute("username");
        String img = userService.getImg(username);
        FileInputStream fileInputStream = new FileInputStream(request.getServletContext().getRealPath("\\upload")+"\\" + img);
        ServletOutputStream outputStream = response.getOutputStream();
        byte[] bytes=new byte[1024];
        int read = fileInputStream.read(bytes);
        while (read!=-1){
            outputStream.write(bytes,0,read);
            read=fileInputStream.read(bytes);
        }

        outputStream.close();
        fileInputStream.close();
    }

    @RequestMapping("/admin/updPassword")
    public R updPassword(String oldPassword,String newPassword1,String newPassword2,HttpSession session){
        if (!newPassword1.equals(newPassword2)){
            return R.fail("修改失败！密码不一致！");
        }
        String username =(String) session.getAttribute("username");
        int i = userService.updPassword(new User(username, oldPassword, null,null),newPassword1);
        if (i==0){
//            未知问题
            return R.fail("修改失败！请联系管理员！");
        }
        if (i==1){
//            修改成功
            return R.ok("修改成功！请重新登录！");
        }
        if (i==2){
//            旧密码不正确
            return R.fail("修改失败！旧密码不正确！");
        }
        return null;
    }

    @RequestMapping("/getYzm")
    public void getYzm(HttpServletRequest request, HttpServletResponse response) throws IOException {
//        生成图片，设置长宽
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(116, 36);
//        保存验证码
        request.getSession().setAttribute("yzm",lineCaptcha.getCode());

//        响应
        ServletOutputStream out = response.getOutputStream();
        lineCaptcha.write(out);
        out.close();
    }

}
